import router from '../router'
import { ref,onMounted } from 'vue'

// 登录状态
let loginFlag = ref(false)
function getLogStatus(){
  let logStatus = window.sessionStorage.getItem("logStatus");
  // console.log(logStatus,loginFlag.value);
    if (logStatus === null) {
      loginFlag.value = false;
    } else {
      loginFlag.value = true;
    }
}
// 目标路径
let toPath = ref('')
// 原路径
let fromPath = ref('')
// 跳转到登录页
const toLogin = () => {
    ElMessageBox.confirm(
      '你还没有登录，立即去登录？',
      '提示',
      {
        confirmButtonText: '登录',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    .then(() => {
        router.push('/login')
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消登录',
      })
    },router.push('/'))
    
  }

  
router.beforeEach((to,from,next) => {
  // 获取原路径
  fromPath.value = from.path
  console.log("to", toPath.value,"\n","from", fromPath.value);
  getLogStatus()
  if(to.path === '/exitLogin'){
    // console.log(to.path);
    window.sessionStorage.removeItem("logStatus");
    next('/')
    ElMessage({
      message: '已退出登录',
      type: 'success',
    })
    // console.log(loginFlag.value);
  }else{
     // 判断是否需要鉴权
     if (to.meta.isAuth){
      if (loginFlag.value) {
        next()
      }else {
        toLogin()
        toPath.value = to.path
      }
    }else{
      next()
    }
  }
    
   
  })

// 页面跳转时更改页面标题
router.afterEach((to,from) => {
    document.title = to.meta.title
})

export default {
      loginFlag,
      toPath,
      fromPath
}
  